package com.example.springdemo8.service;

import ch.qos.logback.core.net.SyslogOutputStream;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.Date;

@Service
public class ServiceDemo {
    private static final String ADMIN_KAPTCHA_SESSION_KEY = "ADMIN_KAPTCHA_SESSION_KEY";
    private static final String ADMIN_KAPTCHA_SESSION_DATE = "ADMIN_KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60 * 1000;

    public boolean check(String captcha, HttpSession session) {
        //1.检验Captcha是否为空
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }
        //2.检查输入的验证码和生成的验证码是否相同
        String saveCaptcha = (String)session.getAttribute(ADMIN_KAPTCHA_SESSION_KEY);
        if(saveCaptcha != null && saveCaptcha.equalsIgnoreCase(captcha)) {
            //3.检查验证码是否过期
            Date saveDate = (Date) session.getAttribute(ADMIN_KAPTCHA_SESSION_DATE);
            if(System.currentTimeMillis() - saveDate.getTime() < TIME_OUT) {
                return true;
            }
        }
        return false;
    }
}
